import os
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import tkinter as tk
from tkinter import scrolledtext
from tkinter import messagebox
from tkinter import Text
import jieba
import re
import requests
from bs4 import BeautifulSoup
import time
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from PIL import Image,ImageTk

class SearchEngineGUI:  # GUI界面
    def __init__(self):
        #主窗口设置
        root = tk.Tk()
        self.root = root
        root.title("Yummy Engine")
        self.root.geometry("900x600+110+110")
        image = Image.open(r"D:\code\pythonProject1\background.png")
        photo = ImageTk.PhotoImage(image)
        background_label = tk.Label(root, image=photo)
        background_label.image = photo
        background_label.place(x=0, y=0, relwidth=1, relheight=1)
        root.iconphoto(False, tk.PhotoImage(file='hamburger.png'))
        #菜单栏输入框设置
        menu = tk.Menu(root)
        root.config(menu=menu)
        about_menu = tk.Menu(menu, tearoff=False)
        about_menu.add_command(label="使用说明",command=self.instruction)
        about_menu.add_command(label="作者",command=self.author)
        menu.add_cascade(label="About", menu=about_menu)
        menu.add_command(label="Exit", command=root.destroy)
        menu.add_command(label="findmore", command=self.findmore)
        menu.add_command(label="browser",command=self.browser)
        # 检索内容输入框设置
        self.search_query_label = tk.Label(self.root, text="检索内容: ")
        self.search_query_label.pack()
        self.search_query_entry = tk.Entry(self.root, width=50)
        self.search_query_entry.pack()
        # 目标文件夹路径输入框设置
        self.folder_path_label = tk.Label(self.root, text="文件夹路径:")
        self.folder_path_label.pack()
        self.folder_path_entry = tk.Entry(self.root, width=50)
        self.folder_path_entry.insert(0,"D:\\code\\pythonProject1\\database\\食谱") #设置默认输入内容
        self.folder_path_entry.pack()
        #目标文件路径输入框设置
        self.file_path_label = tk.Label(self.root, text="目标文件路径:")
        self.file_path_label.pack()
        self.file_path_entry = tk.Entry(self.root, width=50)
        self.file_path_entry.pack()
        #“检索”“打开”按钮设置
        self.search_button = tk.Button(self.root,text="检索",command=self.search)
        self.search_button.pack()
        self.results_path = scrolledtext.ScrolledText(self.root, width=90, height=10)
        self.results_path.pack()
        self.open_button = tk.Button(self.root,text="打开",command=self.open)
        self.open_button.pack()
        self.results_text = scrolledtext.ScrolledText(self.root, width=90, height=25)
        self.results_text.pack()

    #读取文件
    def read_files(self, folder_path):
        texts = {}
        for foldername, subfolders, filenames in os.walk(folder_path):
            for filename in filenames:
                if filename.endswith(".txt"):
                    full_path = os.path.join(foldername, filename)
                    with open(full_path, 'r', encoding='utf-8') as file:
                        content = file.read()
                        texts[full_path] = content
        return texts

    #进行分词
    def divide_word(self, texts):
        b=[]
        for text in texts.values():
            a=[]
            if text.isalpha():
                a.append(word_tokenize(text))
                b.append(a)
            else:
                a.append((jieba.lcut(text)))
                b.append(a)
        divide_words = dict(zip(texts.keys(), b))
        return divide_words

    # 构建词典,设置停用词
    def dictionary(self, divide_words):
        dictionary=divide_words
        stop_words = set(stopwords.words('english'))
        stopwords_path = "D:\\code\停用词.txt"
        with open(stopwords_path, 'r', encoding='utf-8') as file:
            for line in file:
                stop_words.add(line.strip())

        # 设置停用词
        for text in dictionary.values():
            for words in text:
                i = 0
                while i < len(words):
                    if words[i] in stop_words:
                            # 找到停用词，然后删除它
                        words.pop(i)
                    else:
                        i += 1
        print(dictionary)
        print(stop_words)
        return dictionary

    #检索功能
    def search(self):
        folder_path = self.folder_path_entry.get()
        query = self.search_query_entry.get()

        #检查输入内容
        if not folder_path or not query:
            self.results_path.delete(1.0, tk.END)
            self.results_path.insert(tk.END, "请提供文件夹路径和检索内容。")

        texts = self.read_files(folder_path)#texts是列表
        divide_words = self.divide_word(texts)
        dictionary = self.dictionary(divide_words)

        results = []
        file_names = []
        for key, value in dictionary.items():
            for words in value:
                for word in words:
                    if query in word:
                        file_names.append(key)
        file_names1=set(file_names)

        for file_name in file_names1:
            file_path =os.path.join(folder_path,file_name)  # 拼接文件路径
            results.append(file_path)  # 添加匹配结果
        self.results_path.delete(1.0, tk.END)
        print(results)

        if results:
            for result in results:
                file_path = result
                self.results_path.insert(tk.END, f"{file_path}\n")
            return file_path
        else:
            self.results_path.insert(tk.END, "未找到匹配项。")

    #打开指定文件，读取文件内容
    def open(self):
        s = self.file_path_entry.get()
        if s:
            pattern = r'.*?txt'
            match = re.search(pattern, s)
            if match:
                result_file_path = match.group()
            with open(result_file_path, 'r',
                      encoding='utf-8') as f:
                result_file_content = f.read()
            self.results_text.delete(1.0, tk.END)
            self.results_text.insert(tk.END, result_file_content+"\n\n\n粘贴链接到右上方browser里可了解更多哦")
        else:
            self.results_text.delete(1.0, tk.END)
            self.results_text.insert(tk.END, "请输入目标文件名到指定区域。")
    #作者
    def author(self):
        messagebox.showinfo("author", "作者：宋知行")

    #使用说明
    def instruction(self):
        messagebox.showinfo("使用说明", "1，输入检索内容，点击“检索”，您可以在主页检索食谱库中已有食谱，得到其文件地址。\n2，复制您想要的地址到目标文件路径，点击“打开”，您可以得到文件内容。\n3，如果您对文件内容感兴趣，可以进一步拷贝文档内网页地址，点击上方菜单栏“browser”，将网页地址粘贴到输入框中，点击搜索，将会自动为您跳转该食谱详情页。（仅支持edge浏览器）\n4，如果您不满足于食谱库中的内容，点击上方菜单栏“findmore”，输入您想要的美食名，系统会更新食谱库内容。\n")

    #findmore子窗口GUI设置
    def findmore(self):
        findmore = tk.Toplevel(self.root)
        findmore.title("探寻新美食")
        findmore.geometry("400x300+0+0")
        findmore.iconphoto(False, tk.PhotoImage(file='hamburger.png'))

        findmore_entry = tk.Entry(findmore)
        findmore_entry.pack()

        menu = tk.Menu(findmore)
        findmore.config(menu=menu)
        menu.add_command(label="exit", command=findmore.destroy)

        findmore_button = tk.Button(findmore, text="寻找新美食", command=lambda: self.xiachufang(findmore_entry.get()))
        findmore_button.pack()
        keyword = findmore_entry.get()
        return keyword

    #browser子窗口GUI设置
    def browser(self):
        browser = tk.Toplevel(self.root)
        browser.title("browser——了解更多")
        browser.geometry("500x400+80+80")
        browser.iconphoto(False, tk.PhotoImage(file='hamburger.png'))

        menu = tk.Menu(browser)
        browser.config(menu=menu)
        menu.add_command(label="exit", command=browser.destroy)
        menu.add_command(label="close_browser", command=self.browser_close)

        browser_entry = tk.Entry(browser)
        browser_entry.pack()

        browser_button = tk.Button(browser, text="搜索", command=lambda: self.browser_open(browser_entry.get()))
        browser_button.pack()
        url = browser_entry.get()
        return url

    #根据关键字，爬取下厨房对应网页
    def xiachufang(self,keyword):
        keyword1=keyword
        foods_list = []
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"}

        # 实现自动翻页
        for j in range(3):
            url = f"https://www.xiachufang.com/search/?keyword={keyword1}&page={j}"
            response = requests.get(url=url, headers=headers)
            # 存储食物数据
            soup = BeautifulSoup(response.text, 'html.parser')  # 解析数据
            inf = soup.find_all('div',
                                class_="recipe recipe-215-horizontal pure-g image-link display-block")  # 找到最小父级共同标签
            for food in inf:
                food_name = food.find('img')['alt']  # 菜名
                food_ingredients = food.find('p', class_='ing ellipsis').text  # 食材
                food_href = 'https://www.xiachufang.com/' + food.find('a')['href']  # 链接
                foods_list.append([food_name, food_href, food_ingredients])  # 把获取的数据添加到列表
                recipe_info = f"菜名：{food_name}\n用料：{food_ingredients}\n步骤链接：{food_href}"
                print(recipe_info)
                folder_path = "D:\\code\\pythonProject1\\database\\食谱"
                file_path = os.path.join(folder_path, f"{food_name}.txt")
                # t+=1
                with open(file_path, "w", encoding="utf-8") as file:
                    file.write(recipe_info)
                    file.close()
                    print(f"《{food_name}》菜谱已生成")

    #跳转浏览器
    def browser_open(self,url):
        service = Service(executable_path='D:\\edgedriver_win64 (1)\\msedgedriver.exe')

        browser = webdriver.Edge(service=service)
        url = url

        browser.maximize_window()
        browser.get(url=url)
        time.sleep(10000)
        return browser
    def browser_close(self,browser):
        browser=browser
        browser.close()






if __name__ == "__main__":
    a = SearchEngineGUI()
    a.root.mainloop()